<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="门店" prop="storeId">
        <el-select
          v-model="queryParams.storeId"
          placeholder="请选择门店"
          clearable
          filterable
          class="!w-150px"
        >
          <el-option
            v-for="dict in storeList"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" border :data="list" :stripe="true" :show-overflow-tooltip="true">

      <el-table-column fixed="left" label="操作" min-width="60" align="center">

        <template #default="scope">
          <el-popover style="position: relative" :visible="popoverVisible == scope.row.id"
                      placement="bottom-start"
                      :width="60">
            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  type="primary"
                  @click="handlePic(scope.row)"
                >
                  上传图片
                </el-button>
              </el-col>
            </el-row>


            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  type="primary"
                  @click="handleChangeRemark(scope.row)"
                >
                  修改备注
                </el-button>
              </el-col>
            </el-row>

            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  type="primary"
                  @click="handleAddPayment(scope.row)"
                >
                  添加付款单
                </el-button>
              </el-col>
            </el-row>

            <div class="popoverCloseBtn" @click="closePopover()">关闭</div>
            <template #reference>
              <img src="@/assets/imgs/more_edit.png" class="linkBtn" @click="lookBind(scope.row)" @contextmenu.prevent="handleRightClick(scope.row.id)"
              />
            </template>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="门店名称" align="center" width="180px" prop="storeName" />
      <el-table-column label="对账金额" align="center" prop="amount" width="100px" />
      <el-table-column label="已付金额" align="center" prop="paidAmount" >
        <template #default="scope">
          <el-input class="text-center-input" style="width: 80px" clearable
                    @change="handleChangePaidAmount(scope.row)" v-model="scope.row.paidAmount"/>
        </template>
      </el-table-column>
      <el-table-column label="抵扣金额" align="center" prop="deductionAmount" >
        <template #default="scope">
          <el-input class="text-center-input" style="width: 80px" clearable
                    @change="handleChangeDeductionAmount(scope.row)" v-model="scope.row.deductionAmount"/>
        </template>
      </el-table-column>

      <el-table-column label="欠款金额" align="center" prop="" >
        <template #default="scope">
          <span>{{getArearAmount(scope.row)}}</span>
        </template>
      </el-table-column>

      <el-table-column label="图片记录" align="center" prop="imgUrl">
        <template #default="scope">
          <el-button link type="primary" @click="handlePic(scope.row)" v-if="scope.row.imgUrl == null">上传</el-button>
          <el-image
            v-else
            style="width: 20px; height: 20px"
            :src="img"
            v-for="(img,index) in scope.row.imgUrl"
            :key="index"
            z-index="1000"
            :initial-index="index"
            hide-on-click-modal
            preview-teleported
            :preview-src-list="scope.row.imgUrl"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark">
        <template #default="scope">
          <el-button link type="primary" v-if="scope.row.remark == null" @click="handleChangeRemark(scope.row)">添加备注</el-button>
          <div class="linkBtn" v-else @click="handleChangeRemark(scope.row)">
            {{scope.row.remark}}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />


    <Dialog title="上传图片" v-model="picDialogVisible" width="50%">
      <el-form v-loading="formLoading">
        <el-form-item label="图片信息" label-width="80px">
          <UploadImgs v-model="picData.imgUrl"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="submitPic" type="primary" :disabled="formLoading">确 定</el-button>
        <el-button @click="picDialogVisible = false">取 消</el-button>
      </template>

    </Dialog>


    <Dialog title="备注信息" v-model="remarkDialogVisible" width="50%">
      <el-form v-loading="formLoading">
        <el-form-item label="图片信息" label-width="80px">
          <el-input type="textarea" v-model="remarkData.remark"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="submitRemark" type="primary" :disabled="formLoading">确 定</el-button>
        <el-button @click="remarkDialogVisible = false">取 消</el-button>
      </template>
    </Dialog>

    <Dialog title="新增付款列表" v-model="paymentDialogVisible" width="80%">
      <el-table v-loading="loading" ref="multipleTableRef"  @selection-change="handleSelectionChange"
                border :data="paymentList" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column type="selection" fixed="left" width="40"/>
        <el-table-column label="门店" min-width="120" prop="storeName"/>
        <el-table-column label="车型" min-width="150" prop="carType"/>
        <el-table-column label="车牌" min-width="120" prop="licensePlate"/>
        <el-table-column label="付款状态" min-width="90" align="center" prop="payStatus">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.DISPATCH_PAY_STATUS" :value="scope.row.payStatus"/>
          </template>
        </el-table-column>
<!--        <el-table-column label="付款金额" align="center" min-width="130" prop="dispatchPrice"/>-->
<!--        <el-table-column label="优惠金额" min-width="90" prop="discountPrice"/>-->

<!--        <el-table-column label="付款账户" min-width="90" prop="payAccount"/>-->
        <el-table-column label="付款方式" min-width="90" align="center" prop="payMode">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.DISPATCH_SETTLE_TYPE" :value="scope.row.payMode"/>
          </template>
        </el-table-column>
<!--        <el-table-column-->
<!--          label="付款时间"-->
<!--          align="center"-->
<!--          prop="payDate"-->
<!--          :formatter="dateFormatter"-->
<!--          width="100px"-->
<!--        />-->

<!--        <el-table-column label="已付金额" min-width="130" align="center" prop="paidAmount"/>-->
        <el-table-column label="未付金额" min-width="130" align="center" prop="unpaidAmount"/>
        <el-table-column label="对账状态" min-width="90" align="center" prop="checkStatus">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.DISPATCH_CHECK_STATUS" :value="scope.row.checkStatus"/>
          </template>
        </el-table-column>
<!--        <el-table-column-->
<!--          label="对账时间"-->
<!--          align="center"-->
<!--          prop="checkDate"-->
<!--          :formatter="dateFormatter"-->
<!--          width="100px"-->
<!--        />-->
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="100px"
        />
        <el-table-column label="订单编号" min-width="160" align="center" prop="no"/>
        <el-table-column label="备注" align="center" prop="remark"/>
      </el-table>
      <!-- 分页 -->


      <template #footer>
        <Pagination
          :total="payTotal"
          v-model:page="payQueryParams.pageNo"
          v-model:limit="payQueryParams.pageSize"
          @pagination="getPaymentList"
        />
        <el-button @click="submitAddPayment" type="primary" :disabled="formLoading">新 增</el-button>
        <el-button @click="paymentDialogVisible = false">取 消</el-button>
      </template>
    </Dialog>

  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <PaymentBatchForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { PaymentBatchApi, PaymentBatchVO } from '@/api/dispatch/paymentbatch'
import PaymentBatchForm from './PaymentBatchForm.vue'
import {StoreApi, StoreVO} from "@/api/dispatch/store";
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
import {OrderApi} from "@/api/dispatch/order";
import {PaymentApi} from "@/api/dispatch/payment";

/** 派单系统 批量付款单记录 列表 */
defineOptions({ name: 'DispatchPaymentBatch' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
import {DICT_TYPE} from '@/utils/dict'
const storeList = ref<StoreVO[]>([])
const popoverVisible = ref(null);
const loading = ref(true) // 列表的加载中
const list = ref<PaymentBatchVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const payTotal = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  dispatchPaymentIds: undefined,
  deductionAmount: undefined,
  amount: undefined,
  paidAmount: undefined,
  storeName: undefined,
  imgUrl: undefined,
  storeId: undefined,
  remark: undefined,
  status: undefined,
  sort: undefined,
  createTime: [],
})


const formLoading = ref(false)
const imgUrl = ref([])
const picDialogVisible = ref(false)

const remarkDialogVisible = ref(false)


const paymentDialogVisible = ref(false)
const multipleTableRef = ref()
const multipleSelection = ref([])
const paymentList = ref([])
const payQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  storeId: undefined,
  checkStatus: 1
})
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const batchId = ref(undefined);

const handleAddPayment = async (row) => {

  batchId.value = row.id;

  paymentDialogVisible.value = true
  payQueryParams.storeId = row.storeId;
  await getPaymentList();

  popoverVisible.value = null;
}

const submitAddPayment = async () => {

  if (multipleSelection.value.length == 0) {
    ElMessage.error('请选择付款单');
    return;
  }
  //新增中...
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '新增中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  try {
    await PaymentApi.bindBatch(batchId.value,multipleSelection.value)
    paymentDialogVisible.value = false;
    getList();
  }finally {
    loadingInstance.close();
  }
}

/** 查询支付列表 */
const getPaymentList = async () => {
  loading.value = true
  try {
    const data = await PaymentApi.getPaymentPage(payQueryParams)
    if (data == null){
      paymentList.value = [];
      payTotal.value =0;
      return;
    }
    let page = data.page;
    paymentList.value = page.list;
    payTotal.value = page.total;
  } finally {
    loading.value = false
  }
}


const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const {push} = useRouter()

const  lookBind = (row) => {

  push({
    path: "/dispatch/finance/payment/payment",
    query: {doType: "query", data: row.dispatchPaymentIds}
  });
}



const closePopover = async () => {
  popoverVisible.value = null;
}
const handleRightClick = (id) => {
  popoverVisible.value = id;
};


const handleChangePaidAmount = async (row) => {
  try{

    //金额不能小于0
    if (row.paidAmount < 0) {
      ElMessage.error('未付金额不能小于0');
      return;
    }

    //是否确认
    if ( await message.confirm('确定要修改未付金额吗?') == false) {
      return;
    }

    await PaymentBatchApi.updatePaidAmount(row);

    //提示
    ElMessage.success('修改成功');

  }finally {
    getList();
  }

}
const remarkData = reactive({
  id: undefined,
  sort: 1,
  status: 0,
  remark: undefined
})
const handleChangeRemark = async (row) => {
  remarkDialogVisible.value = true;
  remarkData.id = row.id;
  remarkData.remark = row.remark;

  popoverVisible.value = null;
}

const getArearAmount = (row) => {
  return row.amount - row.paidAmount - row.deductionAmount;
}

const handlePic = async (row) => {
  picDialogVisible.value = true;
  picData.id = row.id;
  picData.imgUrl = row.imgUrl;

  popoverVisible.value = null;
}
const picData = reactive({
  id: undefined,
  sort: 1,
  status: 0,
  imgUrl: []
})
/**
 * 提交图片信息
 */
const submitPic = async () => {
  formLoading.value = true;
  try {
    await PaymentBatchApi.handlePic(picData);
    message.success(t("处理成功"))
    await getList()
    picDialogVisible.value = false;
  } catch {
  } finally {
    formLoading.value = false;
  }
}


const submitRemark = async () => {
  formLoading.value = true;
  try {
    await PaymentBatchApi.handleRemark(remarkData);
    message.success(t("处理成功"))
    await getList()
    remarkDialogVisible.value = false;
  } catch {
  } finally {
    formLoading.value = false;
  }
}


const handleChangeDeductionAmount = async (row) => {

  try {
    //金额不能小于0
    if (row.deductionAmount < 0) {
      ElMessage.error('抵扣金额不能小于0');
      return;
    }
    if ( await message.confirm('确定要修改抵扣金额吗?') == false) {
      return;
    }

    await PaymentBatchApi.updateDeductionAmount(row);

    //提示
    ElMessage.success('修改成功');
  }finally {
    getList();
  }


}



/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PaymentBatchApi.getPaymentBatchPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PaymentBatchApi.deletePaymentBatch(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await PaymentBatchApi.exportPaymentBatch(queryParams)
    download.excel(data, '派单系统 批量付款单记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  storeList.value = await StoreApi.getStoreSimpleList();
  // getList()//
})

onActivated(() => {
  popoverVisible.value = null;
  getList()
});
</script>
